package com.net.xpay.core.helper;

import com.net.xpay.core.constant.OssChannel;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import com.net.common.util.LocalDateUtil;
import com.net.xpay.core.CoreProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.net.URL;
import java.time.LocalDateTime;

/**
 * 2019/5/19 15:37

 */
@Slf4j
@Component
public class UploadHelper {

    @Autowired
    private CoreProperties coreProperties;

    @Autowired
    private AliyunUploaderHelper aliyunUploaderHelper;

    private COSClient cosClient;

    private synchronized void initClient() {
        if (cosClient != null) {
            return;
        }
        // 1 初始化用户身份信息（secretId, secretKey）
        COSCredentials cred = new BasicCOSCredentials(coreProperties.getOssAccessKey(), coreProperties.getOssSecretKey());
        // 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        // clientConfig中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        ClientConfig clientConfig = new ClientConfig(new Region(coreProperties.getOssRegion()));
        // 3 生成 cos 客户端。
        cosClient = new COSClient(cred, clientConfig);
    }

    public String upload(String fileName, InputStream inputStream, LocalDateTime expiration) {
        if (cosClient == null) {
            initClient();
        }
        //默认路径
        String dir = coreProperties.getOssUploadDir();

        String ossChannel = coreProperties.getOssChannel();
        if (OssChannel.ALIYUN.equals(ossChannel)) {
            return uploadAliyunOss(dir, fileName, inputStream, expiration);
        } else {
            return upload(dir, fileName, inputStream, expiration);
        }

    }

    private String uploadAliyunOss(String dir, String fileName, InputStream inputStream, LocalDateTime expiration) {
        return aliyunUploaderHelper.upload(fileName, inputStream, expiration);
    }

    //默认传到腾讯云
    private String upload(String dir, String fileName, InputStream inputStream, LocalDateTime expiration) {
        if (cosClient == null) {
            initClient();
        }

        PutObjectRequest putObjectRequest = new PutObjectRequest(dir, fileName, inputStream, null);
        cosClient.putObject(putObjectRequest);

        URL url = cosClient.generatePresignedUrl(dir, fileName, LocalDateUtil.toDate(expiration));
        return "https://" + url.getHost() + url.getPath();
    }
}
